package com.bristua.mall.admin.common.utils;


import com.bristua.mall.admin.common.enums.CommonCode;
import com.bristua.mall.admin.common.exception.BizException;
import com.github.pagehelper.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * Created by Administrator on 2017/10/27 0027.
 * 图片工具
 */
@Component
public class PicUtil {
    private static final Logger logger = LoggerFactory.getLogger(PicUtil.class);
    @Autowired
    private HttpRequestUtil httpRequestUtil;

    /**
     * 判断文件目录是否存在
     * @param path
     */
    public void fileDirIsExist(String path) {
        File file = new File(path);
        if (!file.exists() && file.isDirectory()) {
            file.mkdir();
        }
    }

    /**
     * 删除图片
     * @param path
     */
    public void delPic(String path){
        File file = new File(path);
        if(file.isFile()){
            file.delete();
        }
    }

    /**
     * 判断图片是否存在
     *
     * @param path
     * @return
     */
    public boolean fileIsExist(String path) {
        File file = new File(path);
        if (file.exists() && file.isFile()) {
            return true;
        }
        return false;
    }



    /**
     * 图片加载
     *
     * @param path
     */
    public void loadPic(String path) {
        if(!StringUtil.isEmpty(path)){
            File file = new File(path);
            if (file.isFile()) {
                HttpServletResponse response = httpRequestUtil.getResponse();
                response.reset();
                httpRequestUtil.getResponse().setHeader("Prama", "Pragma");
                httpRequestUtil.getResponse().setHeader("Cache-Control", "public");
                httpRequestUtil.getResponse().setDateHeader("Expires", System.currentTimeMillis()+1*60*60*24);
                httpRequestUtil.getResponse().setHeader("Content-Length", file.length() + "");
                ServletOutputStream out = null;
                InputStream in = null;
                try {
                    in = new FileInputStream(file);
                    out = httpRequestUtil.getResponse().getOutputStream();
                    //读取文件流
                    int len = 0;
                    byte[] buffer = new byte[1024 * 10];
                    while ((len = in.read(buffer)) != -1) {
                        out.write(buffer, 0, len);
                    }
                    out.flush();
                } catch (Exception e) {
                    throw new BizException(CommonCode.IMG_LOAD_FAIL.getCode(),CommonCode.IMG_LOAD_FAIL.getMsg(),e);
                } finally {
                    try {
                        out.close();
                        in.close();
                    } catch (Exception e) {
                        throw new BizException(CommonCode.IMG_LOAD_FAIL.getCode(),CommonCode.IMG_LOAD_FAIL.getMsg(),e);
                    }

                }

            }
           
        }

    }


    /**
     * 采用指定宽度、高度或压缩比例 的方式对图片进行压缩
     * @param imgsrc 源图片地址
     * @param imgdist 目标图片地址
     * @param widthdist 压缩后图片宽度（当rate==null时，必传）
     * @param heightdist 压缩后图片高度（当rate==null时，必传）
     * @param rate 压缩比例
     */
//    public static void reduceImg(String imgsrc, String imgdist, int widthdist,
//                                 int heightdist, Float rate) {
//        try {
//            File srcfile = new File(imgsrc);
//            // 检查文件是否存在
//            if (!srcfile.exists()) {
//                return;
//            }
//            // 如果rate不为空说明是按比例压缩
//            if (rate != null && rate > 0) {
//                // 获取文件高度和宽度
//                int[] results = getImgWidth(srcfile);
//                if (results == null || results[0] == 0 || results[1] == 0) {
//                    return;
//                } else {
//                    int width = results[0];
//                    if(width>=550){
//                        rate=0.3F;
//                    }
//                    widthdist = (int) (results[0] * rate);
//                    heightdist = (int) (results[1] * rate);
//                }
//            }
//            // 开始读取文件并进行压缩
//            Image src = javax.imageio.ImageIO.read(srcfile);
//            BufferedImage tag = new BufferedImage((int) widthdist,
//                    (int) heightdist, BufferedImage.TYPE_INT_RGB);
//
//            tag.getGraphics().drawImage(
//                    src.getScaledInstance(widthdist, heightdist,
//                            Image.SCALE_SMOOTH), 0, 0, null);
//
//            FileOutputStream out = new FileOutputStream(imgdist);
//            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//            encoder.encode(tag);
//            out.close();
//
//        } catch (IOException ex) {
//            ex.printStackTrace();
//        }
//    }
    /**
     * 获取图片宽度
     *
     * @param file
     *            图片文件
     * @return 宽度
     */
    public static int[] getImgWidth(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int result[] = { 0, 0 };
        try {
            is = new FileInputStream(file);
            src = javax.imageio.ImageIO.read(is);
            result[0] = src.getWidth(null); // 得到源图宽
            result[1] = src.getHeight(null); // 得到源图高
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
